package com.syn.gmail.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.syn.common.to.es.SkuEsModel;
import com.syn.gmail.search.config.SearchConfig;
import com.syn.gmail.search.constant.EsConstant;
import com.syn.gmail.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productUp(List<SkuEsModel> skuEsModelList) throws IOException {
        //es保存数据
        //用批量插入
        BulkRequest bulkRequest = new BulkRequest();
        for(SkuEsModel model : skuEsModelList){
            //设置请求
            //请求的索引
            IndexRequest index = new IndexRequest(EsConstant.PRODUCT_INDEX);
            index.id(model.getSkuId().toString());
            //把对象转成JSON字符串
            String s = JSON.toJSONString(model);
            //添加源
            index.source(s, XContentType.JSON);
            bulkRequest.add(index);
        }
        BulkResponse reslut = restHighLevelClient.bulk(bulkRequest, SearchConfig.COMMON_OPTIONS);
        //TODO 如果批量错误
        boolean b = reslut.hasFailures();
        List<String> ids = Arrays.stream(reslut.getItems()).map(item->{
            return item.getId();
        }).collect(Collectors.toList());
        log.error("商品上架错误，{}",ids);

        return b;
    }
}
